<script setup lang="ts">
import { watch, onActivated, ref, onBeforeMount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from "../request/request";

import { useUsersStore } from "../store/user";
const store = useUsersStore();


const route = useRoute()
const router = useRouter()
const newsId = ref(route.params.newsId)

const isLoading = ref(true)
const isLoadingLikeButton = ref(true)
const isLiked = ref(false)

watch(isLoading, (n, o) => {
  console.log('watch isLoading', n, o);

})

const news = ref({
  "id": "",
  "title": "",
  "passageContent": "",
  "postTime": "",
  "viewNum": "",
  "commentNum": ""
})


function getFromSessionStoarge(key: string) {
  let valueRaw = sessionStorage.getItem(key)
  if (valueRaw != null) {
    return JSON.parse(valueRaw)
  }
  else {
    return []
  }
}

const getContents = () => {
  isLoading.value = true
  isLoadingLikeButton.value = true
  console.log('in news view');
  console.log('route.params', route.params);

  // 这里的策略是先尝试从session存储和pinia里面拿出来news本体，如果能拿到，则不进行网络请求
  let newsList = getFromSessionStoarge("hot")
  newsList = newsList.concat(getFromSessionStoarge("cf"))
  newsList = newsList.concat(getFromSessionStoarge("vsm"))
  newsList = newsList.concat(getFromSessionStoarge("seen"))

  let flag = false
  for (let index = 0; index < newsList.length; index++) {
    const newsInList = newsList[index];
    // console.log(newsId.value, news.id);
    if (newsInList.id == newsId.value) {
      // 找到了
      console.log('found in session', newsInList.id);
      news.value = newsInList
      flag = true
      // console.log(newsList);

      break
    }
  }

  if (flag == false) {
    // 除了去session找之外，还去pinia里面找
    for (let index = 0; index < store.newsSearchResult.length; index++) {
      const newsInList = store.newsSearchResult[index];
      // console.log(newsId.value, news.id);
      if (newsInList.id == newsId.value) {
        // 找到了
        console.log('found in pinia', newsInList.id);
        news.value = newsInList
        flag = true
        // console.log(newsList);
        break
      }
    }
  }
    
  if (flag == false) {
    // 内存里都没找到，则发请求给后端，去数据库找
    console.log('need send request');
    request.get("/news/find/" + newsId.value).then((response) => {
      console.log(response);
      if (response.data != "") {
        news.value = response.data
        newsId.value = news.value.id;
        // news.value.passageContent = news.value.passageContent.matchAll ("　　", "<br>")
        // news.value.passageContent = news.value.passageContent.replaceAll("　　", "</p><p>")
      }
      else {
        ElMessage(
          {
            message: `似乎没有${newsId.value}这篇新闻，已导航至首条新闻页面`,
            type: 'info',
          })
          console.log('no this newsId');
          newsId.value = "100017383"
          router.replace("/news/" + newsId.value)
          request.get("/news/find/" + newsId.value).then((response) => {
            console.log(response);
            if (response.data != "") {
              news.value = response.data
              newsId.value = news.value.id;
              // news.value.passageContent = news.value.passageContent.replaceAll("　　", "</p><p>")
            }
          })
      }

      doAfterGetContent()


    })
  }
  else {
    doAfterGetContent()
  }

  function doAfterGetContent() {
    isLoading.value = false
    news.value.passageContent = news.value.passageContent.replaceAll("　　", "</p><p>")

    // 最后，发请求确定下这篇文章是否感兴趣过
    let userId = sessionStorage.getItem("userId")
    request.get(`/user_operation/find_by_user_and_news/${userId}/${route.params.newsId}`).then((response) => {
      console.log('isLike?', response);
      if (response.data.length != 0) {
        // 感兴趣过
        isLiked.value = true
      }
      else {
        isLiked.value = false

      }

      isLoadingLikeButton.value = false

      console.log('loading end');

    })
  }

}
onBeforeMount(() => {
  isLoading.value = true
})

onActivated(() => {
  // 调用时机为首次挂载
  // 以及每次从缓存中被重新插入时
  window.scrollTo(0, 0);
  news.value = {
    "id": "",
    "title": "",
    "passageContent": "",
    "postTime": "",
    "viewNum": "",
    "commentNum": ""
  }

  newsId.value = route.params.newsId

  console.log("newsId", newsId.value);
  console.log('onActivated news view');

  getContents()


})


const back = () => {
  router.back()
}

const doLike = () => {
  isLoading.value = true
  // 状态确认
  if (isLiked.value === false) {
    // 数据库增加
    let userId = sessionStorage.getItem("userId")
    request.get(`/user_operation/add/${userId}/${news.value.id}`).then((response) => {
      console.log(response);
      if (response.data != "") {
        // 成功
        isLiked.value = true
      }
      else {
        // 说明数据库中已有记录，不进行操作
      }
      doAfterLikeOrDisLike()
    })
  }
}

const doDisLike = () => {
  isLoading.value = true
  // 状态确认
  if (isLiked.value === true) {
    // 数据库删除
    let userId = sessionStorage.getItem("userId")
    request.get(`/user_operation/del/${userId}/${news.value.id}`).then((response) => {
      console.log(response);
      if (response.data == "") {
        // 成功
        isLiked.value = false
      }
      doAfterLikeOrDisLike()


    })
  }
}

const doAfterLikeOrDisLike = () => {
  // 除了userId之外，清除sessionStorage缓存
  let userId = sessionStorage.getItem("userId") || ""
  sessionStorage.clear()
  sessionStorage.setItem("userId", userId)

  // 还需要清除 pinia 的 newsSearchResult 缓存（因为viewNum变了，上一页搜索结果的内容也要变）
  store.newsSearchResult = []

  // 更新页面内容，实现button 和 viewNum的更新
  getContents()
  // 改变状态量，让主页推荐页面接收到之后注意刷新
  store.needForceRefresh = true

}
</script>


<template>
  <div class="main">



    <div v-loading="isLoading" element-loading-background="#ffffff45" class="index_content">
      <div>
        <h2 class="title" style="display: inline;">
          {{ news.title }}
        </h2>
        <el-button @click="back()" type="success" style="display: inline; float: right; margin-top: 8px;"> 返回 </el-button>

      </div>

      <div class="sub">
        <div class="">

          <div>
            <div style="display: inline;">
              <span>{{ news.postTime.substring(0, 10) }}</span>
            </div>
            <span> ∙ </span>
            <div style="display: inline;">
              <span> {{ news.id }} </span>
            </div>
          </div>
        </div>
        <div>
          <div>兴趣数量 {{ news.viewNum }}</div>
        </div>
      </div>


      <div class="content">
        <p v-html="news.passageContent">

        </p>
      </div>


      <div v-loading="isLoadingLikeButton" element-loading-background="#ffffff45" class="bottom">
        <transition name="bottom-button">
          <el-button v-if="isLiked" type="danger" @click="doDisLike()">取消感兴趣</el-button>
          <el-button v-else type="primary" @click="doLike()">感兴趣</el-button>
        </transition>
      </div>

    </div>


    <el-backtop :right="100" :bottom="100" />


  </div>
</template>

<style scoped>
.v-enter-active,
.v-leave-active {
  transition: opacity 1.5s;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
  transition: opacity 0.5s;
}

.bottom-button-enter-active {
  transition: opacity 0.5s ease;
}

.bottom-button-enter {
  opacity: 0;
}

.bottom-button-leave-active {
  transition: opacity 0.4s;
}

.bottom-button-leave-to {
  opacity: 0;
}


.bottom {
  text-align: center;
  vertical-align: middle;
  min-height: 50px;
}

/* .bottom:hover {
  cursor: progress;
} */


.index_content {
  /* background: #fff; */
  padding: 15px;
  /* min-height: 500px; */
}

.main {
  /* padding-top: 74px; */


  padding: 80px 25vw 80px 25vw;
  padding-top: 82px !important;
  padding-bottom: 80px !important;


  /* min-height: 73vh; */

}

.title {
  font-size: 32px;
  font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
  font-weight: 700;
  color: #000;
  line-height: 42px;
}

.sub {
  display: flex;
  -moz-box-pack: justify;
  justify-content: space-between;
  -moz-box-align: center;
  align-items: center;
  margin: 20px 0 20px;
  font-size: 12px;
  font-family: MicrosoftYaHei;
  color: #999;
  line-height: 18px;
  margin-right: 10px;
}

.content {
  font-family: MicrosoftYaHei;
  color: #333;
  margin: 0 auto;
  line-height: 30px;
  letter-spacing: .5px;
  word-wrap: break-word;
  font-size: 16px;
}

p {
  display: block;
  margin-block-start: 1em;
  margin-block-end: 1em;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
}

a {
  color: #00a5eb;
  text-decoration: none;
  background-color: transparent;
  outline: none;
  cursor: pointer;
  transition: color .3s;
  -webkit-text-decoration-skip: objects;
}

li,
ul {
  list-style: none;
  padding-inline-start: 0px;
}
</style>
